from openpyxl import load_workbook, Workbook
from pathlib import Path
from rich import print as rprint

from sys import path
orign_path = 'd:/python&work'
path.append(orign_path)
from little_function import read, convert


root_path = Path('d:/copy&run')

wb = Workbook()

ledger_root = root_path / '结算支付台账-2024年12月'
ledger_files = read.get_files(ledger_root)
headers = ['序号', '队伍名称', '往来单位名称', '结算金额（含税）', '应付结算款', '实际已付款', '剩余应付款', '部门', '款项性质']
for progromme_name, ledger_file in ledger_files.items():
    rprint(progromme_name)
    ledger_content = read.read_ledger(ledger_file)       # 从结算支付台账中提取数据
    for unit_name, unit_content in ledger_content.copy().items():
        remain_payment = unit_content['剩余应付款']
        if eval(remain_payment) < 1:        # 删除实际为0，但读取为极小数（如；-1.4551915228366852e-11）的情况
            del ledger_content[unit_name]
    wb.create_sheet(progromme_name)
    ws = wb[progromme_name]
    ws.append(headers)
    num = 1
    current_row = 2
    for unit_content in ledger_content.values():
        ws.cell(current_row, 1).value = num
        for col_name in headers[1:]:
            try:
                float(unit_content[col_name])       # 判断是否为数字
            except ValueError:
                value_to_wan = unit_content[col_name]
            else:
                value_to_wan = convert.convert_to_wan(unit_content[col_name])
            ws.cell(current_row, headers.index(col_name)+1).value = value_to_wan
        num += 1
        current_row += 1
wb.save(root_path / 'our_plan.xlsx')
